<?php
namespace app\admin\controller\produce;

use app\admin\model\Order;
use app\admin\model\Produce;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Index extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];
    protected $searchFields = ['produce_sn'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Produce();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            $this->request->get(['filter' => json_encode($filterArr)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $whereNew = [
                'is_delete' => 0
            ];
            $list = $this->model
                ->where($mimetypeQuery)
                ->where($where)
                ->where($whereNew)
                ->order($sort, $order)
                ->paginate($limit)->each(function ($item, $key) {
                    $order = Db::name('order')->alias('o')->join('customer c','c.id = o.customer_id','LEFT')
                        ->field('o.order_sn,c.name as customer_name')->where(['o.id' => $item['order_id']])->find();
                    $item['order'] = $order;
                });

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            $subData['row']['admin_id'] = $this->auth->id;
            $subData['row']['produce_sn'] = generate_unique_order_sn('PUR');

            try {
                Db::startTrans();
                $this->model->allowField(true)->save($subData['row']);
                //添加订单详情
                $productCol = Db::name('product')->where(['is_delete' => 0])->column('name,spec','id');
                $orderDetails = json_decode($subData['row']['test'],true);
                foreach ($orderDetails as $detail) {
                    $orderDetailsData[] = [
                        'produce_id' => $this->model->id,
                        'product_id' => $detail['product_id'],
                        'product_name' => $productCol[$detail['product_id']]['name'] ?? '',
                        'product_spec' => $productCol[$detail['product_id']]['spec'] ?? '',
                        'product_standard' => $detail['product_standard'],
                        'remark' => $detail['remark'],
                        'number' => $detail['number'],
                        'material_worker' => $detail['material_worker'],
                        'lathe_worker' => $detail['lathe_worker'],
                        'driller_worker' => $detail['driller_worker'],
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }
                Db::name('produce_goods')->insertAll($orderDetailsData ?? []);
            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success(' 提交成功');
        }

        // 订单转生产单
        $order_id = $this->request->param('order_id');
        if (!empty($order_id)) {
            $order = (new Order())->find($order_id);
            $detailLists = Db::name('order_goods')->where(['order_id' => $order_id])->field('product_id,product_spec,product_standard,number')->select();
            $order['detail_json'] = json_encode($detailLists,256);
            $this->assign('order', $order ?? 0);
        }


        // 客户列表
        $customerLists = Db::name('customer')->where(['status' => 1,'is_delete' => 0])->field('id,name')->column('name','id');
        $this->assign('customerLists', $customerLists);
        return $this->view->fetch();
    }

    public function edit($ids = "")
    {
        if ($this->request->isAjax()) {
            $subData = $this->request->param();

            try {
                Db::startTrans();
                $model = $this->model->find($ids);
                $model->allowField(true)->save($subData['row']);

                $productCol = Db::name('product')->where(['is_delete' => 0])->column('name,spec','id');
                $orderDetails = json_decode($subData['row']['test'],true);
                foreach ($orderDetails as $detail) {
                    $orderDetailsData[] = [
                        'produce_id' => $ids,
                        'product_id' => $detail['product_id'],
                        'product_name' => $productCol[$detail['product_id']]['name'] ?? '',
                        'product_spec' => !empty($detail['product_spec']) ? $detail['product_spec'] : $productCol[$detail['product_id']]['spec'] ?? '',
                        'product_standard' => $detail['product_standard'],
                        'remark' => $detail['remark'],
                        'number' => $detail['number'],
                        'material_worker' => $detail['material_worker'],
                        'lathe_worker' => $detail['lathe_worker'],
                        'driller_worker' => $detail['driller_worker'],
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }
                Db::name('produce_goods')->where(['produce_id' => $ids])->delete();
                Db::name('produce_goods')->insertAll($orderDetailsData ?? []);
            }catch (Exception $exception) {
                Db::rollback();
                $this->error('提交失败：'.$exception->getMessage());
            }
            Db::commit();
            $this->success('修改成功');
        }

        // 获取车间生产单和订单数据
        $produce = $this->model->find($ids);
        $detailLists = Db::name('produce_goods')->where(['produce_id' => $ids])->select();
        $produce['detail_json'] = json_encode($detailLists,256);
        $this->assign('produce', $produce);

        $order_id = $produce['order_id'];
        $order = (new Order())->find($order_id);
        $this->assign('order', $order ?? 0);

        // 客户列表
        $customerLists = Db::name('customer')->where(['status' => 1,'is_delete' => 0])->field('id,name')->column('name','id');
        $this->assign('customerLists', $customerLists);
        return $this->view->fetch();
    }

    public function finish($ids)
    {
        $produce = $this->model->find($ids);
        if (!empty($produce) && $produce['finish_status'] == 0) {
            $produce->finish_status = strtotime($produce['finish_status']) > time() ? 1:2;
            $produce->actual_finish_time = date('Y-m-d', time());
            $produce->save();
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    // 打印
    public function print(){
        $ids = $this->request->get('id');
        $ids = explode(',',$ids);
        $lists = $this->model->where('id','in',$ids)->select();
        $sum_amount = 0;
        foreach ($lists as &$value){
            $goods_info = Db::name('produce_goods')->where('produce_id',$value['id'])->select();
            $sum_amount += array_sum(array_column($goods_info,'amount'));
            $value['goods_info'] = $goods_info;

            $value['sum_amount'] = $sum_amount;
        }
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    // 详情
    public function detail($ids = '')
    {
        $detail = $this->model->find($ids);
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $detail['details'] = Db::name('produce_goods')->where(['produce_id' => $detail['id']])->select();

        $this->assign('order', $detail);

        return $this->view->fetch();
    }
}
